//
//  OneEngine.swift
//  yihuiwang_mac
//
//  Created by 张衡 on 2020/10/30.
//  Copyright © 2020 1meeting. All rights reserved.
//

import Foundation

struct OptionData: HandyJSON {
    var isjoin:Bool = true
    var name:String?
    var roomid:String?
    var password:String?
    var ownid:String?
    var number:String?
    
    //房间号加密
    var encryption:String?
}


class OneEngine: NSObject {
    static let shared = OneEngine.init()
}

//MARK:- 加入会议
extension OneEngine {
    func gojoinmeeting(roomid:String,userid:String,enterSuccess:os_block_t?,enterFail:os_block_t?,resultPassword:os_block_t?) {
        RtcEngine.responseJoin(roomid: roomid, userid: userid) { _ in
            self.enterTrtcEngine(roomid: roomid, userid: userid)
            if enterSuccess != nil {
                enterSuccess!()
            }
        } fail: {
            if enterFail != nil {
                enterFail!()
            }
        } passwrodResult: { _ in
            self.enterPasswordAndCLOSE { (string) in
                self.enterTrtcEngine(roomid: roomid, userid: userid)
            }
            if resultPassword != nil {
                resultPassword!()
            }
        }
    }
    
    func enterPasswordAndCLOSE(success:ResultString?) {
        TrtcEngine.close(classs: [MainViewController.classForCoder()])
        self.enterPassword { (string) in
            TrtcEngine.close(classs: [MeetingPasswordViewController.classForCoder()])
            if success != nil {
                success!(string)
            }
        } close: {
            TrtcEngine.exit()
        }

    }
    
    func enterPassword(success:ResultString?,close:os_block_t?) {
        TrtcEngine.meetingPasswordOrderFront { (string) in
            if Td.sh().cloud.passwordCloud == string {
                if success != nil {
                    success!(string)
                }
                
            }else {
                show_msg("密码错误")
            }
        } closeBlock: {
            if close != nil {
                close!()
            }
        }
    }
    
    
    func enterTrtcEngine(roomid:String,userid:String)  {
        //设置本地信息x摄像头，静音举手id
        Td.sh().lc.userId = userid
        Td.sh().lc.nickName = Td.sh().name
        Td.sh().lc.isAdc = true
        Td.sh().params.role = .audience
        
        var info = OneInfo()
        info.roomId = roomid
        info.userId = userid
        self.doJoinMeeting(info:info)
        
        TrtcEngine.enter()
    }
    
    func doJoinMeeting(info:OneInfo) {
        let roomid = info.roomId
        let userid = info.userId
        LoadWindow.show()
        IMEngine.shared.sdkAuto()
        IMEngine.shared.login(id:userid!,succ: {
            LoadWindow.dismss()
            IMEngine.shared.getJoinedGroupList(groupId: roomid!, succ: { (isok) in
                if isok == true {
                    self.joinMeeting()
                }else {
                    IMEngine.shared.joinGroup(groupId: roomid!, succ: {
                        self.joinMeeting()
                    }) { (code, msg) in
                        switch code {
                        case 10010:
                            self.joinMeeting()
                        default:
                            break
                        }
                        show_msg("code = \(code),msg = \(msg ?? "未知")")
                    }
                }
            }) { (code, msg) in
                show_msg("code = \(code),msg = \(msg ?? "未知")")
            }
            
        }) { (code, msg) in
            LoadWindow.dismss()
            show_msg("code = \(code),msg = \(msg ?? "未知")")
        }
        
    }
    
    func joinMeeting() {
        let mode = Plist_historyMode.init(roomId: Td.sh().params.roomId!, name: "1meeting 会议")
        PLISTSaveManager.appendAndSave(mode: mode)
        TrtcEngine.joinTrtcOrderFront()
    }
    
    
}


//MARK:- 召开会议
extension OneEngine {
    func gohostmeeting(ownid:String,enterSuccess:os_block_t?,enterFail:os_block_t?) {
        let scence = (Td.sh().scene == .meeting) ? "0":"1"
        RtcEngine.responseHost(scene: scence, ownid: ownid, success: { (result) in
            self.doHostmeetingandData(enterSuccess:enterSuccess)
        }) { (result) in
            self.meetingLast(enterSuccess: enterSuccess)
        }
    }
    
    func meetingLast(enterSuccess:os_block_t?) {
        guard let roomid = Td.sh().params.roomId else {return}
        let controller = KlViewController.init(title: "会议状态", massage: "你已经召开一个会议，若你想召开新的会议，必须结束上一次会议!", buttomTitles: ["结束上一场会议","回到会议","取消"], indexBlock: { (index, control) in
            if index == 0 {
                control.startLoading()
                NetEngine.requseLastExitRoom(roomId: roomid) {
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                        control.stopLoading()
                        control.kl_dismiss(nil)
                    }
                }
            }else if index == 1 {
                self.goBack(roomid: roomid, enterSuccess: enterSuccess)
                control.kl_dismiss(nil)
            }else  if index == 2 {
                control.kl_dismiss(nil)
            }
        }, navBlock: nil)
        controller.isDismiss = false
        let window = NSWindow.init(contentViewController: controller)
        //window.centerIn(window: self.view.window)
        window.makeKeyAndOrderFront(nil)
    }
    
    func doHostmeetingandData(enterSuccess:os_block_t?)  {
        guard let roomid = Td.sh().params.roomId,let userid = Td.sh().params.userId else {
            return
        }
        //设置本地信息x摄像头，静音举手id
        Td.sh().lc.userId = userid
        Td.sh().lc.nickName = Td.sh().name
        Td.sh().params.role = .anchor
        
        var info = OneInfo()
        info.roomId = roomid
        info.userId = userid
        self.dohostMeeting(info:info)
        
        TrtcEngine.enter()
        if enterSuccess != nil {
            enterSuccess!()
        }
    }
    
    //进入会议
    func dohostMeeting(info:OneInfo)  {
        let roomid = info.roomId
        let userid = info.userId
        LoadWindow.show()
        IMEngine.shared.sdkAuto()
        IMEngine.shared.login(id:userid!,succ: {
            LoadWindow.dismss()
            //设置名字
            IMEngine.shared.updateNickName(name:Td.sh().lc.nickName, succ: nil, fail: nil)
            IMEngine.shared.getGroupInfo(groupId: roomid!, succ: { (isok) in
                if isok == true{
                    self.hostMeeting()
                }else {
                    IMEngine.shared.createGroup(name: roomid!, groupId: roomid!, succ: {
                        self.hostMeeting()
                    }) { (code, msg) in
                        show_msg("code = \(code),msg = \(msg ?? "")")
                    }
                }
            }) { (code, msg) in
                show_msg("code = \(code),msg = \(msg ?? "")")
            }
            
        }) { (code, msg) in
            LoadWindow.dismss()
            show_msg("code = \(code),msg = \(msg ?? "")")
        }
    }
    
    
    func goBack(roomid:String,enterSuccess:os_block_t?) {
        RtcEngine.responseLastHostMeeting(roomid: roomid) { (result) in
            self.doHostmeetingandData(enterSuccess: enterSuccess)
        }
    }
    
    func hostMeeting() {
        TrtcEngine.hostTrtcOrderFront()
    }
    
}
